import { _decorator, Component, Node, Animation, macro, Vec2, v2, v3, Vec3, Prefab, instantiate, find } from 'cc';
import { PrefabEnum } from '../common/PrefabEnum';
import ResManager from '../common/ResManager';

const { ccclass, property } = _decorator;

export enum  MonsterState{
    UP = 'up',
    DOWN = 'down',
    LEFT = 'left',
    RIGHT = 'right',
    LEFT_UP = 'leftUp',
    LEFT_DWON = 'leftDown',
    RIGHT_UP = 'rightUp',
    RIGHT_DOWN = 'rightDown',
}

@ccclass('Monster')
export class Monster extends Component {

    public animation:Animation
    public speed:number = 10
    public dir:Vec2 = v2(0, 0)

    public stateList:MonsterState[] = [
        MonsterState.UP, MonsterState.DOWN, MonsterState.LEFT, MonsterState.RIGHT,
        MonsterState.LEFT_UP, MonsterState.LEFT_DWON, 
        MonsterState.RIGHT_UP, MonsterState.RIGHT_DOWN
    ]

    /**
     * 创建野怪
     * @param prefab 野怪的prefab路径
     * @param pos 野怪出生点的世界坐标
     */
    static async createMonster(prefab:PrefabEnum, pos:Vec3):Promise<Node>{
        let monster = await ResManager.instance.loadAssetByUrl<Prefab>(prefab)
        let monsterNode = instantiate(monster)
        find('Canvas').addChild(monsterNode)
        monsterNode.worldPosition = pos
        return monsterNode
    }

    protected onLoad(): void {
        this.animation = this.node.getComponent(Animation)
    }

    start() {

        this.changeState()
        this.schedule(this.changeState, 5, macro.REPEAT_FOREVER)
    }

    update(deltaTime: number) {
        
        let dir3 = v3(this.dir.x, this.dir.y, 0)
        this.node.translate(dir3.multiplyScalar(this.speed * deltaTime))
    }

    changeState(){
        let ran = Math.floor(Math.random() * 8) 
       
        let state = this.stateList[ran]

        this.animation.play(state)

        switch(state){
            case MonsterState.UP:
                this.dir = v2(0, 1)
            break
            case MonsterState.DOWN:
                this.dir = v2(0, -1)
            break
            case MonsterState.LEFT:
                this.dir = v2(-1, 0)
            break
            case MonsterState.RIGHT:
                this.dir = v2(1, 0)
            break
            case MonsterState.LEFT_DWON:
                this.dir = v2(-1, -1)
            break
            case MonsterState.LEFT_UP:
                this.dir = v2(-1, 1)
            break
            case MonsterState.RIGHT_DOWN:
                this.dir = v2(1, -1)
            break
            case MonsterState.RIGHT_UP:
                this.dir = v2(1, 1)
            break
        }
    }
}


